package com.gaojiawei.multiThread05_ThreeSpecialAtomic;

import org.junit.Test;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用lock保证原子性
 */
public class l06_AtomicWithLock {
    private ReentrantLock lock = new ReentrantLock();

    private int count;

    @Test
    public void testLock() throws InterruptedException {
        Thread thread = new Thread(() -> {
            sync();
        });

        Thread thread1 = new Thread(() -> {
            sync();
        });

        thread.start();
        thread1.start();

        Thread.sleep(3000);
        System.out.println(count);
    }


    public void sync(){
        for(int i = 0;i<1000;i++){
            lock.lock();
            try {
                count++;
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //lock 代码发生异常的时候不会自动释放锁，因此在实际使用的时候注意把他放到finally代码块当中
                lock.unlock();
            }

        }
    }
}
